package cn.itcast.service.system.impl;

import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserService userService;

    @Override
    public PageInfo<User> findByPage(String companyId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userDao.findAll(companyId);
        return new PageInfo<>(list);
    }

    @Override
    public User findById(String userId) {
        return userDao.findById(userId);
    }

    @Override
    public List<User> findAll(String companyId) {
        return userDao.findAll(companyId);
    }

    @Override
    public void save(User user) {
        user.setId(UUID.randomUUID().toString());
        String md5Hash = new Md5Hash(user.getPassword(), user.getEmail()).toString();
        user.setPassword(md5Hash);
        userDao.save(user);
    }

    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public boolean delete(String id) {

        //-- 删除前先查询当前删除的数据是否有被引用
        //SELECT COUNT(*) FROM pe_role_user WHERE user_id=''
        Long count = userDao.findUserRoleByUserId(id);

        //-- 如果有被引用，不能删除
        //DELETE FROM pe_user WHERE user_id=''
        if (count == 0) {
            userDao.delete(id);
            return true;
        }
        return false;
    }

    @Override
    public void changeRole(String userId, String[] roleIds) {
        //-- 用户分配角色
        //1. 先解除用户角色的关系
        //DELETE FROM pe_role_user WHERE user_id=''
        userDao.deleteUserRoleByUserId(userId);

        //2. 用户添加角色
        //INSERT INTO pe_role_user(user_id,role_id)VALUES('','')
        if (roleIds != null && roleIds.length > 0){
            for (String roleId : roleIds) {
                userDao.saveUserRole(userId,roleId);
            }
        }
    }

    @Override
    public User findByEmail(String email) {
        return userDao.findByEmail(email);
    }


}
